<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { Modal, Message, RequestOption } from '@arco-design/web-vue';
  import { useForm } from '@/hooks/arco/useForm';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';
  import { useUploader } from '@/hooks/useUploader';
  import { queryInstDepartments } from '@/api/structure-management/department';
  import { queryInstPositions } from '@/api/structure-management/position';
  import {
    createStaff,
    updateStaff,
    genCertificateUploadToken,
    queryStaffCertificates,
  } from '@/api/structure-management/employee';
  import * as Lodash from 'lodash';
  import { validateIdCard } from '@/utils/validate';
  import { 
    fillData, 
    getInfoFromImageResource,
    getIdsFromArcoImages,
  } from '@/views/lhj-v1/util';

  const loading = ref(false);
  const emits = defineEmits(['cancel', 'save']);
  const props = withDefaults(
    defineProps<{
      data?: any;
      visible?: boolean;
      title?: string;
      type: 'add' | 'edit';
    }>(),
    {
      visible: false,
      title: '查看',
    }
  );

  const baseNameMap = {
    itemId: { key: 'staffId', label: '员工ID' },
    itemName: {
      key: 'staffName',
      label: '员工姓名',
      placeholder: '请输入员工姓名',
    },
    itemIDCard: {
      key: 'idCardNo',
      label: '身份证号',
      placeholder: '请输入身份证号',
    },
    itemGender: {
      key: 'gender',
      label: '员工性别',
      placeholder: '请选择员工性别',
    },
    itemBirthday: {
      key: 'birthday',
      label: '出生日期',
      placeholder: '请选择出生日期',
    },
    itemPhone: {
      key: 'phoneNo',
      label: '联系电话',
      placeholder: '请输入联系电话',
    },
    itemAddress: {
      key: 'address',
      label: '通讯地址',
      placeholder: '请输入通讯地址',
    },
    itemStatus: {
      key: 'jobStatus',
      label: '就职状态',
      placeholder: '请选择就职状态',
    },
    itemStatusTitle: { key: 'jobStatusTitle', label: '就职状态' },
    itemDepartment: {
      key: 'department',
      label: '所属部门',
      placeholder: '请选择所属部门',
    },
    departmentIds: {key: 'departmentIds'},
    itemPosition: {
      key: 'position',
      label: '所在岗位',
      placeholder: '请选择所在岗位',
    },
    positionIds: {key: 'positionIds'},
    itemQuals: { key: 'certificateResIds', label: '资质证件（非必填）' },
    btnAction: { label: '操作' },
    btnLook: { label: '查看' },
  };

  const genderOptions = [
    { label: '未知', value: 0 },
    { label: '男', value: 1 },
    { label: '女', value: 2 },
  ];

  const jobStatusOptions = [
    { label: '在职', value: 1 },
    { label: '离职', value: 2 },
  ];

  const departmentSelect = useSelectOption({
    name: baseNameMap.itemDepartment.label,
    apiFun: queryInstDepartments,
    fieldNames: {
      label: 'name',
      value: 'id',
    },
  });

  const positionSelect = useSelectOption({
    name: baseNameMap.itemPosition.label,
    apiFun: queryInstPositions,
    fieldNames: {
      label: 'name',
      value: 'id',
    },
  });

  const itemForm = useForm({
    state: {
      [baseNameMap.itemId.key]: '',
      [baseNameMap.itemName.key]: '',
      [baseNameMap.itemGender.key]: '',
      [baseNameMap.itemBirthday.key]: '',
      [baseNameMap.itemPhone.key]: '',
      [baseNameMap.itemIDCard.key]: '',
      [baseNameMap.itemAddress.key]: '',
      [baseNameMap.itemStatus.key]: '',
      [baseNameMap.itemDepartment.key]: '',
      [baseNameMap.itemPosition.key]: '',
      [baseNameMap.itemQuals.key]: [],
    } as any,
    rules: {
      [baseNameMap.itemName.key]: {
        required: true,
        message: baseNameMap.itemName.placeholder,
      },
      [baseNameMap.itemGender.key]: {
        required: true,
        message: baseNameMap.itemGender.placeholder,
      },
      [baseNameMap.itemBirthday.key]: {
        required: true,
        message: baseNameMap.itemBirthday.placeholder,
      },
      [baseNameMap.itemPhone.key]: {
        required: true,
        message: baseNameMap.itemPhone.placeholder,
      },
      [baseNameMap.itemIDCard.key]: {
        required: true,
        message: baseNameMap.itemIDCard.placeholder,
      },
      [baseNameMap.itemAddress.key]: {
        required: true,
        message: baseNameMap.itemAddress.placeholder,
      },
      [baseNameMap.itemStatus.key]: {
        required: true,
        message: baseNameMap.itemStatus.placeholder,
      },
      [baseNameMap.itemDepartment.key]: {
        required: true,
        message: baseNameMap.itemDepartment.placeholder,
      },
      [baseNameMap.itemPosition.key]: {
        required: true,
        message: baseNameMap.itemPosition.placeholder,
      },
    },
  });

  const uploader = useUploader({
    props: {
      listType: 'picture',
      defaultFileList: [],
    },
    apiFun: genCertificateUploadToken,
    onOk: (result) => {
      console.log('upload ok:', result)
    },
  });

  const handleDrawerSave = () => {
    itemForm
      .validate()
      .then(() => {
        loading.value = true;
        // let modalContent = '确认新增员工？';
        let messageText = '新增成功！';
        let apiFunc: any = createStaff;
        const jsonData: any = Lodash.cloneDeep(itemForm.state);
        // 处理数据
        if (jsonData[baseNameMap.itemDepartment.key]) {
          jsonData[baseNameMap.departmentIds.key] = [jsonData[baseNameMap.itemDepartment.key]];
        }
        if (jsonData[baseNameMap.itemPosition.key]) {
          jsonData[baseNameMap.positionIds.key] = [jsonData[baseNameMap.itemPosition.key]];
        }
        // 资质证书
        jsonData[baseNameMap.itemQuals.key] = uploader.getResourceIds();
        if (props.type === 'edit') {
          // modalContent = '确认保存员工信息？';
          messageText = '保存成功！';
          apiFunc = updateStaff;
          // apiFunc = null;
          // console.log(jsonData);
        } else if (props.type === 'add') {
          // jsonData.ll = '';
        } else {
          return;
        }
        if (!apiFunc) return;
        apiFunc(jsonData)
          .then(() => {
            Message.success(messageText);
            // pageTable.reload();
            // itemForm.resetFields();
            itemForm.backToInit();
            emits('cancel');
            emits('save');
          })
          .finally(() => {
            loading.value = false;
          });
        // [zxj:update] 按要求删除
        // Modal.confirm({
        //   title: '提示',
        //   bodyStyle: 'text-align: center;',
        //   content: modalContent,
        //   onOk: (e) =>{

        //   },
        //   onCancel(e) {
        //     loading.value = false;
        //   },
        // });
      })
      .catch((err) => {
        console.error(err);
      });
  };

  watch(
    () => props.data,
    (newVal) => {
      if (newVal) {
        const data = Lodash.cloneDeep(newVal);
        if (data.departments && data.departments.length > 0) {
          data.department = data.departments[0].departmentId;
        }
        if (data.positions && data.positions.length > 0) {
          data.position = data.positions[0].positionId;
        }
        fillData(itemForm.state, data);
      }
    },
    { immediate: true, deep: true }
  );

  // 实时计算 `性别`、`出生日期`
  watch(
    () => itemForm.state[baseNameMap.itemIDCard.key],
    (newVal) => {
      if (newVal && validateIdCard(newVal)) {
        const gender = newVal.substring(16, 17) % 2 === 0 ? 2 : 1;
        itemForm.state[baseNameMap.itemGender.key] = gender;
        const date = newVal.substring(6, 14);
        itemForm.state[baseNameMap.itemBirthday.key] = `${date.substring(
          0,
          4
        )}-${date.substring(4, 6)}-${date.substring(6)}`;
      }
    }
  );

  watch(()=>props.visible, (newVal)=>{
    if (newVal && props.data[baseNameMap.itemId.key]) {
      uploader.props.defaultFileList = [];
      const imgItems = Lodash.cloneDeep(props.data[baseNameMap.itemQuals.key])
      for (let i=0 ; i<imgItems.length; i+=1) {
        uploader.props.defaultFileList?.push(getInfoFromImageResource(imgItems[i]))
      }
    }
  }, {immediate: false});
</script>

<template>
  <div class="m-employee-edit">
    <a-drawer
      :width="400"
      :visible="props.visible"
      unmount-on-close
      @cancel="emits('cancel')"
    >
      <template #title>{{ props.title }}</template>
      <div>
        <a-form v-bind="itemForm.bindProps" layout="vertical">
          <!-- 员工姓名 -->
          <a-form-item
            :field="baseNameMap.itemName.key"
            :label="baseNameMap.itemName.label"
          >
            <a-input
              v-model="itemForm.state[baseNameMap.itemName.key]"
              :placeholder="baseNameMap.itemName.placeholder"
              allow-clear
            />
          </a-form-item>
          <!-- 身份证号 -->
          <a-form-item
            :field="baseNameMap.itemIDCard.key"
            :label="baseNameMap.itemIDCard.label"
          >
            <a-input
              v-model="itemForm.state[baseNameMap.itemIDCard.key]"
              :max-length="18"
              :placeholder="baseNameMap.itemIDCard.placeholder"
              allow-clear
            />
          </a-form-item>
          <!-- 员工性别 -->
          <a-form-item
            :field="baseNameMap.itemGender.key"
            :label="baseNameMap.itemGender.label"
          >
            <a-select
              v-model="itemForm.state[baseNameMap.itemGender.key]"
              :placeholder="baseNameMap.itemGender.placeholder"
              allow-clear
            >
              <a-option
                v-for="(item, index) of genderOptions"
                :key="'gender-' + index"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>
          <!-- 出生日期 -->
          <a-form-item
            :field="baseNameMap.itemBirthday.key"
            :label="baseNameMap.itemBirthday.label"
          >
            <a-date-picker
              v-model="itemForm.state[baseNameMap.itemBirthday.key]"
              style="width: 100%"
              :placeholder="baseNameMap.itemBirthday.placeholder"
              allow-clear
            />
          </a-form-item>
          <!-- 联系电话 -->
          <a-form-item
            :field="baseNameMap.itemPhone.key"
            :label="baseNameMap.itemPhone.label"
          >
            <a-input
              v-model="itemForm.state[baseNameMap.itemPhone.key]"
              :placeholder="baseNameMap.itemPhone.placeholder"
              allow-clear
            />
          </a-form-item>
          <!-- 通讯地址 -->
          <a-form-item
            :field="baseNameMap.itemAddress.key"
            :label="baseNameMap.itemAddress.label"
          >
            <a-input
              v-model="itemForm.state[baseNameMap.itemAddress.key]"
              :placeholder="baseNameMap.itemAddress.placeholder"
              allow-clear
            />
          </a-form-item>
          <!-- 就职状态 -->
          <a-form-item
            :field="baseNameMap.itemStatus.key"
            :label="baseNameMap.itemStatus.label"
          >
            <a-select
              v-model="itemForm.state[baseNameMap.itemStatus.key]"
              :placeholder="baseNameMap.itemStatus.placeholder"
              allow-clear
            >
              <a-option
                v-for="(item, index) of jobStatusOptions"
                :key="'jobStatus-' + index"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>
          <!-- 所属部门 -->
          <a-form-item
            :field="baseNameMap.itemDepartment.key"
            :label="baseNameMap.itemDepartment.label"
          >
            <a-select
              v-model="itemForm.state[baseNameMap.itemDepartment.key]"
              v-bind="departmentSelect.bindProps"
              :placeholder="baseNameMap.itemDepartment.placeholder"
              allow-clear
            />
          </a-form-item>
          <!-- 所在岗位 -->
          <a-form-item
            :field="baseNameMap.itemPosition.key"
            :label="baseNameMap.itemPosition.label"
          >
            <a-select
              v-model="itemForm.state[baseNameMap.itemPosition.key]"
              v-bind="positionSelect.bindProps"
              :placeholder="baseNameMap.itemPosition.placeholder"
              allow-clear
            />
          </a-form-item>
          <!-- 资质证件（非必填） -->
          <a-form-item
            :label="baseNameMap.itemQuals.label"
          >
            <a-upload v-bind="uploader.props" @change="uploader.handleChange" @before-remove="uploader.handleBeforeRemove"/>
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <ae-button purpose="cancel" @click="emits('cancel')">取消</ae-button>
        <ae-button purpose="save" @click="handleDrawerSave">保存</ae-button>
      </template>
    </a-drawer>
  </div>
</template>

<style lang="less" scoped>
  .m-employee-edit {
  }
</style>
